<template>
  <div :class="[prefixCls, {[`${prefixCls}-rootnode`]: level === 0}]">
    <div :class="[`${prefixCls}__title`, {[`${prefixCls}__title-selected`]: data.selected}]">
      <span :class="arrowClasses" @click="handleExpand">
        <i v-if="showLoading" class="xvu-iconfont xvu-spinner"></i>
        <i v-else-if="showArrow" :class="arrowIconClasses"></i>
      </span>
      <span :class="`${prefixCls}__title_text`" @click="handleSelect">{{ data.title }}</span>
    </div>
    <div :class="`${prefixCls}__content`" :style="contentStyle">
      <x-tree-node
        v-for="(item, i) in children"
        :key="i"
        :data="item"
        :level="level + 1"
        :children-key="childrenKey"
      ></x-tree-node>
    </div>
  </div>
</template>
<script>
import Emitter from '@/script/mixins/emitter'
const prefixCls = 'x-tree-node'
export default {
  name: 'x-tree-node',
  mixins: [Emitter],
  props: {
    data: {
      type: Object,
      default () {
        return {}
      }
    },
    level: {
      type: Number,
      default: 0
    },
    childrenKey: {
      type: String,
      default: 'children'
    }
  },
  data() {
    return {
      prefixCls: prefixCls
    }
  },
  computed: {
    children () {
      return this.data[this.childrenKey]
    },
    arrowClasses () {
      return [
        `${prefixCls}__title_arrow`,
        {
          [`${prefixCls}__title_arrow_disabled`]: this.data.disabled,
          [`${prefixCls}__title_arrow_open`]: this.data.expand
        }
      ]
    },
    arrowIconClasses () {
      let result = []
      if (this.children.length === 0) result = []
      else if (this.level === 0) result = ['xvu-iconfont', 'xvu-rhombus-halffill']
      else if (this.level > 0) result = ['xvu-iconfont', 'xvu-rhombus']
      return result.join(' ')
    },
    contentStyle () {
      return {
        'max-height': this.data.expand ? `10000px` : `0px`
      }
    },
    showArrow () {
      return (this.data[this.childrenKey] && this.data[this.childrenKey].length) || ('loading' in this.data && !this.data.loading)
    },
    showLoading () {
      return 'loading' in this.data && this.data.loading
    }
  },
  methods: {
    handleExpand () {
      const item = this.data
      if (item.disabled) return
      if (item[this.childrenKey] && item[this.childrenKey].length) {
        this.$set(this.data, 'expand', !this.data.expand)
        this.dispatch('Tree', 'toggle-expand', this.data)
      }
    },
    handleSelect () {
      if (this.data.disabled) return
      this.dispatch('Tree', 'on-selected', this.data.nodeKey)
    }
  }
}
</script>
